/**
 * Created by yanghaijin on 2018/5/15.
 */
let MongoDBUtil = require('./../../../util/MongoDBUtil');
let RoomIdGenerator = require('./../../../util/RoomIdGenerator');

const MsgCode = require('./../../../define/MsgCode');
const ErrorCode = require('./../../../define/ErrorCode');
const CodeString = require('./../../../define/CodeString');
const MAP_ID = require('./../../../define/MAP_ID');
const MapID2ServerID = require('../../../define/MapID2ServerID');

module.exports = function (app) {
    return new Handler(app);
};

let Handler = function (app) {
    this.app = app;
    app.roomHandler = this;
};

/**
 * 加入房间
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next stemp callback
 * @return {void}
 */
Handler.prototype.createRoom = function (msg, session, next) {
    console.log('session.uid', session.uid);
    let self = this;
    let room_id = RoomIdGenerator.getRoomId();
    console.info('生成一个RoomID', room_id);
    let map_id = msg['data'].map_id;
    const server_id = MapID2ServerID[map_id]; // 根据map_id 连接不同的游戏服务
    if (server_id) {
        this.app.rpc[server_id]['Remote'].createRoom(session, session.get('info'), this.app.get('serverId'), room_id, msg['data'], function (code, players) {
            // 房间信息与玩家会话信息绑定
            session.set('room_id', room_id);
            session.push('room_id', function (err) {
                if (err) {
                    console.error('set room_id for session service failed! error is : %j', err.stack);
                    next(null, {
                        code: MsgCode.JoinRoom,
                        errorCode: ErrorCode.Room_Full,
                        data: {
                            msg: CodeString[ErrorCode.Room_Full]
                        }
                    });
                } else {
                    let data = msg['data'];
                    data['map_id'] = map_id;
                    data['room_id'] = room_id;
                    data['players'] = players;
                    data['msg'] = CodeString[MsgCode.CreateRoom];
                    next(null, {
                        code: MsgCode.JoinRoom,
                        data: data
                    });

                    // 记录房间
                    self.app.id2mapid[room_id] = map_id;

                    self.app.roomid2mapid[room_id] = map_id;

                    self.app.uid2roomid[session.uid] = room_id;

                    console.log('已有房间列表：', self.app.uid2roomid);
                }
            });
        });
    } else {
        console.info('没有配置该类型的房间，创建房间失败！');
    }
};

/**
 * 加入房间
 * @param  {Object}   msg     request message
 * @param  {Object}   session current session object
 * @param  {Function} next    next stemp callback
 * @return {void}
 */
Handler.prototype.joinRoom = function (msg, session, next) {
    if (!msg['data'].hasOwnProperty('room_id')) {
        console.info('【roomHandler】消息中没有房间号');
        return;
    }
    let room_id = msg['data']['room_id'];
    if (!this.app.roomid2mapid.hasOwnProperty(room_id)) {
        console.log('不能寻找到房间号【' + room_id + '】对应的玩法id【roomid2mapid】');
        return;
    }
    let map_id = this.app.roomid2mapid[room_id];
    if (!MapID2ServerID.hasOwnProperty(map_id)) {
        console.info('不能将玩法【' + map_id + '】转化成Server');
        return;
    }
    let self = this;
    this.app.rpc[MapID2ServerID[map_id]]['Remote'].joinRoom(session, session.get('info'), this.app.get('serverId'), room_id, function (msg) {
        console.log('msg = ', msg);
        let code = msg['code'];
        let players = msg['players'];
        console.log('roomHandler code', code, 'players', players);
        switch (code) {
            case MsgCode.JoinRoom:
                // 房间信息与玩家会话信息绑定
                session.set('room_id', room_id);
                session.push('room_id', function (err) {
                    if (err) {
                        console.error('set room_id for session service failed! error is : %j', err.stack);
                    } else {
                        self.app.uid2roomid[session.uid] = room_id;
                        console.log('uid2roomid', self.app.uid2roomid);
                    }
                });
                break;
            case ErrorCode.Room_Full:
                console.log('房间满员了');
                break;
            case ErrorCode.Room_Nonexistence:
                console.log('房间不存在');
                break;
            default:
                break;
        }
    });

    /*
     return;

     let room_id = msg['data'].room_id;
     if (!room_id) {
     next(null, {
     code: MsgCode.JoinRoom,
     errorCode: ErrorCode.Room_ID_Error,
     data: {
     msg: CodeString[ErrorCode.Room_ID_Error]
     }
     });
     }

     let self = this;
     let callback = function (map_id, code, players) {
     if (code === MsgCode.JoinRoom) {
     // 房间信息与玩家会话信息绑定
     session.set('room_id', room_id);
     session.push('room_id', function (err) {
     if (err) {
     console.error('set room_id for session service failed! error is : %j', err.stack);
     next(null, {
     code: MsgCode.JoinRoom,
     errorCode: ErrorCode.Room_Full,
     data: {
     msg: CodeString[ErrorCode.Room_Full]
     }
     });
     } else {
     let data = msg['data'];
     // data['map_id'] = MAP_ID.SPELL_THREE;
     data['map_id'] = map_id;
     data['room_id'] = room_id;
     data['players'] = players;
     next(null, {
     code: MsgCode.JoinRoom,
     data: data
     });
     self.app.uid2roomid[session.uid] = room_id;
     }
     });
     } else if (code === ErrorCode.Room_Nonexistence) {
     next(null, {
     code: MsgCode.JoinRoom,
     errorCode: ErrorCode.Room_Nonexistence,
     data: {
     msg: CodeString[ErrorCode.Room_Nonexistence]
     }
     });
     } else {
     console.log('没有处理信息');
     }
     };

     if (!this.app.id2mapid.hasOwnProperty(room_id)) {
     callback(null, ErrorCode.Room_Nonexistence, null);
     console.info('加入房间失败！不存在该房间！');
     return;
     }
     let map_id = this.app.id2mapid[room_id];
     console.info('map_id = ' + map_id);
     switch (map_id) {
     case MAP_ID.SPELL_THREE:
     this.app.rpc.psz.pszRemote.joinRoom(session, session.get('info'), this.app.get('serverId'), room_id, false, null, function (code, players) {
     callback(map_id, code, players);
     });
     break;
     case MAP_ID.TEN_THIRTY:
     console.info('remote====this.app.rpc.tenThirty.Remote.joinRoom');
     this.app.rpc.tenThirty.Remote.joinRoom(session, session.get('info'), this.app.get('serverId'), room_id, false, null, function (code, players) {
     callback(map_id, code, players);
     });
     break;
     default:
     console.error('传入map_id有误');
     break;
     }
     */
};

/**
 * 接收来自客户端的通知
 * @param {Object} msg
 * @param {Object} session
 * @param {Function} next
 * */
Handler.prototype.onNotify = function (msg, session, next) {
    next();
    let self = this;
    let uid = msg['data']['uid'];
    let code = msg['code'];

    switch (code) {
        case MsgCode.CreateRoom:
            this.createRoom(msg, session, next);
            break;
        case MsgCode.JoinRoom:
            this.joinRoom(msg, session, next);
            break;
        default:
            // 后台服务器进行处理逻辑
            if (!msg['data'].hasOwnProperty('room_id')) {
                console.info('【roomHandler】消息中没有房间号');
                break;
            }
            let room_id = msg['data']['room_id'];
            if (!this.app.roomid2mapid.hasOwnProperty(room_id)) {
                console.log('不能寻找到房间号【' + room_id + '】对应的玩法id【roomid2mapid】');
                break;
            }
            let map_id = this.app.roomid2mapid[room_id];
            if (!MapID2ServerID.hasOwnProperty(map_id)) {
                console.info('不能将玩法【' + map_id + '】转化成Server');
                break;
            }
            this.app.rpc[MapID2ServerID[map_id]]['Remote'].onNotify(session, msg, this.app.get('serverId'), function (code) {
                switch (code) {
                    case MsgCode.JoinRoom:
                        console.info('connector加入房间');
                        break;
                    case MsgCode.DissolveRoom:
                        delete self.app.roomid2mapid[room_id];
                        delete self.app.uid2roomid[uid];
                        console.info('删除房间【' + room_id + '】', self.app.roomid2mapid);
                        console.info('房间管理【' + uid + '】', self.app.uid2roomid);
                        break;
                    default:
                        console.info('connetor未处理的code:' + code);
                        break;
                }
            });
            break;
    }
    // next();
};